package com.ruoyi.framework.web.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pay.domain.PayCoinUserForm;
import com.ruoyi.pay.service.IPayCoinUserService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wq.domain.WqFriendApply;
import com.ruoyi.wq.domain.WqQun;
import com.ruoyi.wq.domain.WqUserQun;
import com.ruoyi.wq.domain.vo.WqFriendApplyVO;
import com.ruoyi.wq.service.IWqQunService;
import com.ruoyi.wq.service.IWqUserQunService;
import com.ruoyi.wx.domain.WxMaMsgForm;
import com.ruoyi.wx.service.WxMsgService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;

@Component
public class QunService {
	
	@Autowired
	private IWqUserQunService wqUserQunService;
	
	@Autowired
	private IWqQunService wqQunService;
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
    private IPayCoinUserService payCoinUserService;
	
	@Autowired
	private FriendApplyService friendApplyService;
	
	@Autowired
    private WxMsgService wxMsgService;

	public synchronized WqFriendApplyVO joinQun(WqQun wqQun) {
		Long userId = SecurityUtils.getUserId();
		SysUser user = sysUserService.getById(userId);
		if(StringUtils.isBlank(user.getSex())){
			throw new ServiceException("请选择性别", 521);
		}
		WqQun qun = wqQunService.getById(wqQun.getId());
		// 匹配需要消耗趣豆
		Integer coinNum = 0;
		if("1".equals(user.getIsBlack())){
			boolean flag = false;
			if(user.getVipEndTime() == null){
				flag = true;
			}else{
				Date now = new Date();
				if(now.compareTo(user.getVipEndTime()) > 0){
					flag = true;
				}
			}
			
			if(flag){
				coinNum = 20;
				Integer amount = payCoinUserService.getAmount();
				if(coinNum > amount){
					// 趣豆不足
					throw new ServiceException("匹配需要【"+coinNum+"】趣豆，请充值",799);
				}
			}
			
		}
    	
		WqFriendApplyVO friendApplyVO = new WqFriendApplyVO();
		List<WqUserQun> uqList = wqUserQunService.getUserQunListBySex(wqQun.getId(), user.getSex());
		if(CollectionUtils.isEmpty(uqList)){
			// 加入队伍
			WqUserQun userQun = wqUserQunService.getIsPay(wqQun.getId(), userId);
			if(userQun == null){
				userQun = new WqUserQun();
				userQun.setQunId(wqQun.getId());
				userQun.setUserId(user.getUserId());
				userQun.setAvatar(user.getAvatar());
				userQun.setSex(user.getSex());
				wqUserQunService.saveOrUpdate(userQun);
			}else{
				userQun.setStatus("0");
				wqUserQunService.updateById(userQun);
			}
			
			// 排队成功
			throw new ServiceException("已排队成功，匹配成功后会发送站内信通知", 520);
		}else{
			// 加入队伍
			WqUserQun userQun = wqUserQunService.getIsPay(wqQun.getId(), userId);
			if(userQun == null){
				userQun = new WqUserQun();
				userQun.setQunId(wqQun.getId());
				userQun.setUserId(user.getUserId());
				userQun.setAvatar(user.getAvatar());
				userQun.setSex(user.getSex());
				wqUserQunService.saveOrUpdate(userQun);
			}else{
				userQun.setStatus("0");
				wqUserQunService.updateById(userQun);
			}
			
			// 随机取一个用户
			// 匹配成功创建聊天房间
			WqUserQun randomUser = RandomUtil.randomEle(uqList);
			SysUser u = sysUserService.getById(randomUser.getUserId());
    		WqFriendApply wqFriendApply = new WqFriendApply();
    		wqFriendApply.setUserId(randomUser.getUserId());
    		wqFriendApply.setMessage(qun.getTitle());
    		friendApplyVO = friendApplyService.addCardWechat(wqFriendApply);
    		// 删除被匹配的用户
    		wqUserQunService.deleteWqUserQunByUserId(wqQun.getId(), randomUser.getUserId());
    		
    		WxMaMsgForm form = new WxMaMsgForm();
			form.setAppId(u.getAppId());
			form.setOpenId(u.getOpenId());
			Map<String,String> map = new HashMap<>();
			map.put("phrase1", "活动通知");
			map.put("date2", DateUtil.now());
			map.put("name3", user.getNickName());
			map.put("thing4", "好友匹配成功通知");
			form.setDataMap(map);
			form.setPage("pages/index?index=3");
			wxMsgService.sendSubscribeMsg(form);
			
			PayCoinUserForm payCoinUserForm = new PayCoinUserForm();
    		payCoinUserForm.setUserId(userId);
    		payCoinUserForm.setCoinNum(coinNum);
    		payCoinUserForm.setCoinType("1");
    		payCoinUserForm.setSourceId(qun.getId());
    		payCoinUserForm.setRemark("匹配消费");
    		payCoinUserService.savePayCoinUser(payCoinUserForm);
		}
		
		return friendApplyVO;
	}

	public synchronized boolean add(WqQun wqQun) {
		// 防止重复发布
		if(StringUtils.isNotBlank(wqQun.getUid())){
			QueryWrapper<WqQun> queryWrapper = new QueryWrapper<>();
			WqQun entity = new WqQun();
			entity.setUid(wqQun.getUid());
			queryWrapper.setEntity(entity);
			Integer count = wqQunService.count(queryWrapper);
			if(count > 0){
				return true;
			}
		}
		if("0".equals(wqQun.getPayCheck())){
			// 消费趣豆
			Integer coinNum = 500;
			Integer amount = payCoinUserService.getAmount();
			if(coinNum > amount){
				// 趣豆不足
				throw new ServiceException("推广上墙需要【"+coinNum+"】趣豆，请充值",888);
			}
		}
		
		SysUser user = sysUserService.getById(SecurityUtils.getUserId());
		wqQun.setUserId(user.getUserId());
		wqQun.setAvatar(user.getAvatar());
		wqQun.setSex(user.getSex());
		wqQun.setNickName(user.getNickName());
		wqQun.setOutTime(DateUtil.offsetDay(new Date(), 1));
		wqQun.setStatus("1");
		wqQunService.saveOrUpdate(wqQun);
		return true;
	}
}
